package spring_learn.a05.myProcessor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.context.annotation.AnnotationBeanNameGenerator;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.stereotype.Component;
import spring_learn.a05.Config;

import java.io.IOException;


//自定义beanfactory后处理器，解析componentScan注解，并且把对应包的有component注解的类注册到bean工厂
public class ComponentScanPostProcessor implements BeanDefinitionRegistryPostProcessor {

    /**
     * 1. Spring 操作元数据的工具类 CachingMetadataReaderFactory
     * 2. 通过注解元数据（AnnotationMetadata）获取直接或间接标注的注解信息
     * 3. 通过类元数据（ClassMetadata）获取类名，AnnotationBeanNameGenerator 生成 bean 名
     * 4. 解析元数据是基于 ASM 技术
     *
     *
     * 通过获取Config类中的componentscan注解的值，找到要扫描的类，并且对于类上带有component属性的类进行注册
     */
    private static final Logger logger= LoggerFactory.getLogger(ComponentScanPostProcessor.class);
    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        try {
            ComponentScan annotation = AnnotationUtils.findAnnotation(Config.class, ComponentScan.class);
            if (annotation != null) {
                for (String s : annotation.value()) {
                    logger.info(s);
                    String path = "classpath*:" + s.replace(".", "/") + "/**/*.class";
                    CachingMetadataReaderFactory cachingMetadataReaderFactory = new CachingMetadataReaderFactory();
                    Resource[] resources = new PathMatchingResourcePatternResolver().getResources(path);
                    AnnotationBeanNameGenerator annotationBeanNameGenerator = new AnnotationBeanNameGenerator();
                    for (Resource resource : resources) {
                        MetadataReader metadataReader = cachingMetadataReaderFactory.getMetadataReader(resource);
                        AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata();
                        if (annotationMetadata.hasAnnotation(Component.class.getName())
                                ||annotationMetadata.hasMetaAnnotation(Component.class.getName())){
                            AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.
                                    genericBeanDefinition(metadataReader.getClassMetadata().getClassName()).getBeanDefinition();
                            String beanName = annotationBeanNameGenerator.generateBeanName(beanDefinition, registry);
                            registry.registerBeanDefinition(beanName,beanDefinition);
                        }
                    }

                }
            }
        }catch (Exception e){
            logger.error(e.toString());
        }
    }
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {

    }
}
